package com.minis.web.bind;


import com.minis.beans.mvc.AbstractPropertyAccessor;
import com.minis.beans.mvc.PropertyEditor;
import com.minis.beans.factory.config.PropertyValues;
import com.minis.util.WebUtils;
import com.minis.web.bind.support.BeanWrapperImpl;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Map;

/**
 * 转换并绑定 Request 请求内的字符串参数
 */
public class WebDataBinder {
    private Object target;
    private Class<?> clz;
    private  String objectName;
    AbstractPropertyAccessor propertyAccessor;

    public WebDataBinder(Object target) {
        this(target, "");
    }

    public WebDataBinder(Object target, String targetName) {
        this.target = target;
        this.objectName = targetName;
        this.clz = this.target.getClass();
        this.propertyAccessor = new BeanWrapperImpl(this.target);
    }

    // 绑定的核心方法
    public void bind(HttpServletRequest request) {
        // 将 Request 参数解析成 PropertyValues
        PropertyValues mpvs = assignParameters(request);
        addBindValues(mpvs, request);
        // 绑定
        doBind(mpvs);
    }

    private PropertyValues assignParameters(HttpServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "");
        return new PropertyValues(map);
    }

    protected void addBindValues(PropertyValues mpvs, HttpServletRequest request) {
    }

    private void doBind(PropertyValues mpvs) {
        applyPropertyValues(mpvs);
    }

    // 将参数值与对象属性进行绑定
    protected void applyPropertyValues(PropertyValues mpvs) {
        getPropertyAccessor().setPropertyValues(mpvs);
    }

    // 设置属性值的工具
    protected AbstractPropertyAccessor getPropertyAccessor() {
        return this.propertyAccessor;
    }

    // 自定义转换器
    public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {
        getPropertyAccessor().registerCustomEditor(requiredType, propertyEditor);
    }
}
